<?php

namespace App\Http\Controllers\Api\v1;


use App\Handlers\KeysHandler;
use App\Models\Configuration;
use App\Models\Coupon;
use App\Models\CouponConfig;
use App\Models\GoodsOrder;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests\Api\v1\CouponRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class CouponController extends Controller
{

    //店铺统计
    //all (全部) , activation (可用,购买的券),impending(即将到期)
    public function mycoupons(Request $request)
    {
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        $type = $request->type;
        $coupon_configs = CouponConfig::query()->where('state','=',1)->get();
        foreach ($coupon_configs as $key =>$coupon_config){
            //判断用户是否已领取
            $coupon_config->receive = 0; //未领取
            $coupon_config->expiration_time = null; //未领取
            $coupon = Coupon::query()->where('user_id','=',$user->id)->where('coupon_config_id','=',$coupon_config->id)->first();
            if($coupon){
                $coupon_config->receive = 1; //已领取
                $coupon_config->expiration_time = $coupon->expiration_time; //未领取
                if(Carbon::parse($coupon->expiration_time)->timestamp < now()->timestamp){
                    $coupon_config->receive = 2; //已过期
                }
                //剩余额度
                $coupon_config->quota = $coupon_config->quota - $coupon->used_quota;
                if($coupon_config->quota <= 0){
                    unset($coupon_configs[$key]);
                }
            }

            //不展示未领取的 不展示已过期的
            if($type == 'activation' && (!$coupon || $coupon_config->receive == 2)){
                unset($coupon_configs[$key]);
            }

            //不展示未领取的 不展示非12小时内过期的
            if($type == 'impending' && (!$coupon || Carbon::parse($coupon->expiration_time)->timestamp - now()->timestamp > 12 * 60 *60 )){
                unset($coupon_configs[$key]);
            }

        }
        return $this->success($coupon_configs);
    }

    //领取优惠卷
    public function store(CouponRequest $request){
        $user = User::getUser(['tiktokid'=>$request->header('Userid')]);
        $coupon_config = CouponConfig::find($request->coupon_config_id);
        if(!$coupon_config){
            $this->errorResponse(Response::HTTP_OK, trans('error.700001'), 700001);
        }
        if(!Coupon::query()->where('user_id',$user->id)->where('coupon_config_id',$request->coupon_config_id)->exists()){
            Coupon::query()->create([
                'user_id' => $user->id,
                'coupon_config_id' => $request->coupon_config_id,
                'quota' => $coupon_config->quota,
                'receive_time' => now(),
                'expiration_time' => Carbon::now()->addHours($coupon_config->valid_hour)
            ]);
        }
        return $this->success();
    }


}
